const exception_1 = require('../../core/exception')

const lodash_1 = require("lodash");

const util_1 = require('../../core/util')

// 挂在success方法
const success = (app) => {
  app.context.success = function (obj) {
      this.type = 'application/json';
      const suc = new exception_1.Success(obj);
      let data = {
          errCode: suc.errCode,
          errMsg: suc.errMsg
      };
      this.status = suc.code;
      this.body = JSON.stringify(data);
  };
};

/**
 * json序列化扩展
 *
 * ```js
 * ctx.json({ msg:"hello from lin!" })
 * ```
 *
 * @param app app实例
 */
const json = (app) => {
  /**
   * hide 表示想要隐藏的属性
   */
  app.context.json = function (obj, hide = []) {
      this.type = 'application/json';
      util_1.unsets(obj, hide);
      let data = Object.create(null);
      lodash_1.set(data, 'errCode', 0);
      lodash_1.set(data, 'errMsg', 'ok');
      lodash_1.set(data, 'data', obj);
      this.status = 200;
      this.body = JSON.stringify(data);
  };
};

module.exports = {
  success,
  json
}
